package com.nut.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nut.course.common.Result;
import com.nut.course.entity.Department;
import com.nut.course.mapper.BizDepartmentMapper;
import com.nut.course.service.DepartmentService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private WxCpService wxCpService;

    @Autowired
    private BizDepartmentMapper bizDepartmentMapper;

    @Override
    public Result<List<Department>> list() {

        List<Department> departments = bizDepartmentMapper.selectList(null);
        return Result.ok(departments);

//        try {
//            List<WxCpDepart> list = wxCpService.getDepartmentService().list(null);
//            return Result.ok(list);
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//        }
//        return Result.fail();
    }

    @Override
    public Result syncData() {
        try {

            List<WxCpDepart> list = wxCpService.getDepartmentService().list(null);

            bizDepartmentMapper.delete(new LambdaQueryWrapper<Department>().gt(Department::getId, 0));

            for (WxCpDepart wxCpDepart : list) {
                Department department = new Department();
                department.setId(wxCpDepart.getId());
                department.setName(wxCpDepart.getName());
                bizDepartmentMapper.insert(department);
            }

        } catch (WxErrorException e) {
            e.printStackTrace();
            return Result.fail();
        }
        return Result.ok();

    }


}
